﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QSqlDatabase"
#include "QDebug"
#include "QFont"
#include "QTimer"
#include "QTime"
#include "QBitmap"
#include "QMessageBox"
#include "QFile"
#include "QDir"
#include "QDate"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    Init_All();

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::Init_All()
/*
*功能：初始化控件
*
*/
{

    //界面启动测试当前电脑含有的sql驱动
    ui->textBrowser->append(QStringLiteral("当前电脑包含以下数据库驱动："));
    QStringList drivers = QSqlDatabase::drivers();
    foreach (QString driver, drivers) {
        this->Message_Show(driver);
    }
    this->Message_Show(QStringLiteral("END"));

    //    QTimer *timer = new QTimer();
    //    timer->start(1000);
    //    connect(timer,SIGNAL(timeout()),this,SLOT(Time_Handle()));

    //初始化按钮
    login_sta = log_out_account;
    butten_state(login_sta);

    //设置窗口的标题
    setWindowTitle(QStringLiteral("完美生活   oyangmail@qq.com support  "));
    //设置窗口的背景图片
    //根据图片的数量每次打开不同的背景
    QDir icon_dir("../bin/icon/");
    QStringList filter;
    srand((unsigned)time(NULL));
    QFileInfoList fileInfoList = icon_dir.entryInfoList(filter);
    int count  = fileInfoList.count()-2;
    int rand_num = 2+rand()%count;
    QString file_name = fileInfoList.at(rand_num).fileName();
    QString path = QString("../bin/icon/%1").arg(file_name);
//    qDebug()<<file_name<<rand_num<<" "<<count;
    QPixmap bkgnd(path);
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);
}

void MainWindow::butten_state(char sta)
{
    switch (sta) {
    case log_out_account:
        //账簿相关按钮
        ui->pushButton->hide();
        ui->pushButton_2->hide();
        ui->pushButton_3->hide();

        //显示其他按钮
        ui->pushButton_6->show();
        ui->pushButton_7->show();

        //登录按钮
        ui->pushButton_5->setText(QStringLiteral("登录账簿系统"));
     break;
     case logged_in_account:
        //其他按钮
        ui->pushButton->show();
        ui->pushButton_2->show();
        ui->pushButton_3->show();
        ui->pushButton->setEnabled(1);
        ui->pushButton_2->setEnabled(1);
        ui->pushButton_3->setEnabled(1);
        //登录按钮
        ui->pushButton_5->setText(QStringLiteral("退出登录"));

        //隐藏其他按钮
        ui->pushButton_6->hide();
        ui->pushButton_7->hide();
    break;
    case logged_in_flower :

        //隐藏其他按钮

        ui->pushButton_5->hide();
        ui->pushButton_6->hide();
        ui->pushButton_7->hide();

    }

}

void MainWindow::Time_Handle()
/*
*功能：定时器函数
*
*/
{
    static int sec=0, min=0;
    sec++;
    if(sec>=60)
    {
        min++;
        if(min>20)
        {
            min=0;
            Copy_File();
        }
    }
}


void MainWindow::Copy_File()
/*
*功能：文件定时备份处理
*
*/
{
    static int count=0;
   //QFile::copy(dir1.path()+"/"+copyfile_name,dir2.path()+"/"+copyfile_name))
    QString time = QDate::currentDate().toString();
    QString path =QDir::currentPath(); //  获取当前工程目录
    qDebug()<<path+"/"+"mydata.db";
    qDebug()<<path+"/"+"BackUp"+"/"+time+"_Backup.db";
    QFile::copy(path+"/"+"mydata.db",path+"/"+"BackUp"+"/"+time.simplified()+QString::number(count)+"_Backup.db");
    count++;
}

/*******************************新建/删除 账簿组相关   开始***************************************/
void MainWindow::show_group_widget(QString select)
{
    w = new QWidget();
    bt_yes = new QPushButton(QStringLiteral("确认"));
    if(select == "CREATE")
        connect(bt_yes,SIGNAL(clicked()),this,SLOT(create_group()));
    else
        connect(bt_yes,SIGNAL(clicked()),this,SLOT(cancel_group()));
    QLabel* lable1 = new QLabel(QStringLiteral("账簿名称："));
    creat_acc_edit = new QLineEdit();
    QHBoxLayout *layout2 = new QHBoxLayout();
    layout2->addWidget(lable1);
    layout2->addWidget(creat_acc_edit);
    QVBoxLayout * layout = new QVBoxLayout();
    layout->addLayout(layout2);
    layout->addWidget(bt_yes);
    w->setLayout(layout);
    w->show();

}

void MainWindow::on_pushButton_clicked()
/*
 *新建账簿按钮
 *
 */
{
    show_group_widget("CREATE");
}

void MainWindow::create_group()
{
    QString edit_text = creat_acc_edit->text();
    if(edit_text.isEmpty()){
        QMessageBox::information(this, QStringLiteral("提示"),
         QStringLiteral("账簿名称不能为空！"), QMessageBox::Ok);
    }
    else{
        char meg = logged_account_db->insert_group_data(edit_text);
        if(meg == logged_account_db->I_EXIST)
            this->Message_Show(QStringLiteral("插入组名已存在，请更换组名！"));
        else if(meg == logged_account_db->I_FALSE)
            this->Message_Show(QStringLiteral("新建组名失败，请检查数据库连接！"));
        else{
            this->Message_Show(QStringLiteral("新建组名 %1 成功！").arg(edit_text));
            update_groups();//添加分组后就需要更新显示
            w->close();
        }
    }
}

void MainWindow::update_groups()
/*
 * 每次新建组和用户登录后，都需要对已经存在的组进行更新
 */
{
    QStringList g_list =  logged_account_db->account_find_groups();
    emit update_group_data(g_list);
}

void MainWindow::on_pushButton_3_clicked()
{

    int chooce = QMessageBox::warning(this,QStringLiteral("提示"),
     QStringLiteral("删除账簿会清除关于此账簿的所有记录！请确认是否继续"), QMessageBox::Ok|QMessageBox::Cancel);
    if (chooce == QMessageBox::Ok)
        show_group_widget("CANCEL");
}

void MainWindow::cancel_group()
{
    QString edit_text = creat_acc_edit->text();
    if(edit_text.isEmpty()){
        QMessageBox::information(this, QStringLiteral("提示"),
         QStringLiteral("账簿名称不能为空！"), QMessageBox::Ok);
    }
    else{
        logged_account_db->delete_relation_data_match("groupName", edit_text);
        char meg = logged_account_db->delate_group_data(edit_text);
        if(meg == logged_account_db->I_NOT_EXIST)
            this->Message_Show(QStringLiteral("组名不存在，请确定组名是否存在！"));
        else if(meg == logged_account_db->I_FALSE)
            this->Message_Show(QStringLiteral("删除组名失败，请检查数据库连接！"));
        else{
            this->Message_Show(QStringLiteral("删除组名 %1 成功！").arg(edit_text));
            update_groups();//添加分组后就需要更新显示
            w->close();
        }
    }
}

/******************************* 结束***************************************/


void MainWindow::Message_Show(QString Message)
/*
*功能：用于窗口信息的打印，通过槽函数实现
*
*/
{
    ui->textBrowser->append(Message);
}


void MainWindow::Delate_Win(QString m_Win)
/*
*功能：关闭窗口功能。根据槽函数返回类型判别关闭哪个窗口，同时使能按钮
*
*
*/
{
   if(m_Win=="input")
   {
     delete  m_input;
     Message_Show(QStringLiteral("关闭“账目输入”窗口！"));
   }
   else if(m_Win=="total")
   {
     if(login_sta == logged_in_account)
         ui->pushButton_2->setEnabled(true);
     delete m_total;
     Message_Show(QStringLiteral("关闭“总账查询”窗口！"));
   }
}

/*******************************按钮函数相关   开始***************************************/

void MainWindow::on_pushButton_2_clicked()
/*
*功能：新建总账查询窗口
*
*/
{
    m_total = new Total(this,logged_account_db);
    //添加窗口
    ui->horizontalLayout_2->addWidget(m_total);

    connect(this,SIGNAL(update_group_data(QStringList)),m_total,SLOT(show_groups(QStringList)));
    connect(m_total,SIGNAL(Delate_Win(QString)),this,SLOT(Delate_Win(QString)));
    connect(m_total,SIGNAL(Text_Message(QString)),this,SLOT(Message_Show(QString)));
    ui->pushButton_2->setEnabled(false);
    Message_Show(QStringLiteral("打开“总账查询”窗口！"));

    update_groups();  //必须在所有初始化完成之后更新


}



void MainWindow::on_pushButton_4_clicked()
{
    ui->textBrowser->clear();
}

void MainWindow::on_pushButton_5_clicked()
/*
 * 登录按钮
 * 对于任务逻辑来说，是先登录用户，再根据用户信息打开对应的账簿
 */
{
    if(login_sta == log_out_account){
        w_login = new login(nullptr,"user_info");
        connect(w_login,SIGNAL(login_success(QString, account_db*)),this,SLOT(logged(QString, account_db*)));
        w_login->show();
    }
    else{
        login_sta = log_out_account;
        butten_state(login_sta);  //变更按钮状态
        delete m_input;

        Message_Show(QString(QStringLiteral("用户 ")+" %1 "+QStringLiteral(" 已退出登录！")).arg(log_user));
    }
}

/******************************* 结束***************************************/


void MainWindow::logged(QString user_name, account_db* account_data_db)
/*
 * 登录成功后的槽函数
 */
{
    log_user = user_name;
    logged_account_db = account_data_db;
    Message_Show(QString(QStringLiteral("用户 ")+" %1 "+QStringLiteral(" 登录成功！")).arg(log_user));

    delete  w_login;  //关闭用于登录的临时窗口

    login_sta = logged_in_account;
    butten_state(login_sta);  //变更按钮状态

    m_input = new Input(this, logged_account_db);
    //添加窗口
    ui->horizontalLayout_2->addWidget(m_input);
    //信号和槽的建立一定先有实例化对象后才能建立
    connect(this,SIGNAL(update_group_data(QStringList)),m_input,SLOT(show_groups(QStringList)));
    connect(m_input,SIGNAL(Delate_Win(QString)),this,SLOT(Delate_Win(QString)));
    connect(m_input,SIGNAL(Text_Message(QString)),this,SLOT(Message_Show(QString)));

    update_groups();  //必须在所有初始化完成之后更新
}

void MainWindow::on_pushButton_6_clicked()
{
    login_sta = logged_in_flower;
    butten_state(login_sta);  //变更按钮状态

    m_iov_flower = new Iov_flower();
//    m_flower = new flower(this);
//    m_flower->show();

//    //添加窗口
//    ui->horizontalLayout_2->addWidget(m_flower);

}

void MainWindow::on_pushButton_7_clicked()
{

}
